﻿using MvcPaging;
using Ninject;
using Peninsula.DataAccess.POCO;
using Peninsula.Site.Data.Constant;
using Peninsula.Site.Data.Models;
using Peninsula.Site.Data.Result;
using Peninsula.Utility.Extensions;
using Peninsula.Utility.Helper;
using Peninsula.Web.Areas.Backstage.Models.MaintenanceStaff;
using Peninsula.Web.Areas.Backstage.Models.RepairOrder;
using Peninsula.Web.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Peninsula.Web.Areas.Backstage.Controllers
{
    public class MaintenanceStaffController : AdminBaseController
    {
        TotalList list = new TotalList();


        string[] CateporyMonth = new string[] { "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" };

        [Inject]
        public IServices.IMaintenanceStaffRestatisticsService MaintenanceStaffRestatisticsService { get; set; }

        [Inject]
        public IServices.IMaintenanceStaffService MaintenanceStaffService { get; set; }
        [Inject]
        public IServices.IStoreService StoreService { get; set; }
        [Inject]
        public IServices.IItemTypeService ItemTypeService { get; set; }
        [Inject]
        public IServices.IStoreMangerService StoreMangerService { get; set; }

        [Inject]
        public IServices.IRepairOrderService RepairOrderService { get; set; }

        static string roleName = RoleEnum.MaintenanceStaff.EnumDescription();
        /// <summary>
        /// 查询维修人员
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        // GET: Backstage/MaintenanceStaff
        public ActionResult Index(MaintenanceStaffPagedListModel viewModel)
        {

            SetPageTitle("维修人员");
            // SetBreadcrumb(parentName: "基本管理");
            string storeId = StoreMangerService.GetById(AdminSession.AdminEntity.StoreMangerId).StoreId;
            IQueryable<Admin> query = AdminManager.AdminProvider.Entities.Where(q => q.MaintenanceStafId != null&&q.MaintenanceStaff.StoreId==storeId);
            if (viewModel.Keyword.IsNotNullAndNotWhiteSpace())
            {
                query = query.Where(q => q.UserName.Contains(viewModel.Keyword) ||
                q.TrueName.Contains(viewModel.Keyword) || q.Phone.Contains(viewModel.Keyword)||q.MaintenanceStaff.ItemType.Name.Contains(viewModel.Keyword));

            }
            viewModel.PagedList = query.OrderByDescending(s => s.CreatedTime).ToPagedList(viewModel.PageIndex, viewModel.Size);
            viewModel.QueryParameter = GetParameterFromQueryString();
            return View(viewModel);
        }

        /// <summary>
        /// 编辑或新增维修人员
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CreateOrEditMaintenanceStaff(string id)
        {
            Peninsula.DataAccess.POCO.Admin admin = null;

            if (id.IsNotNullAndNotWhiteSpace())
            {
                admin = AdminManager.Get(a => a.Id == id);
                //admin.MaintenanceStaff.Stores = StoreService.Entities.Select(
                //   s => new SelectListItem()
                //   {
                //       Value = s.Id,
                //       Text = s.Name
                //   }).ToList();
                admin.MaintenanceStaff.ItemTypes = ItemTypeService.Entities.Select(
                   m => new SelectListItem()
                   {
                       Value = m.Id,
                       Text = m.Name
                   }).ToList();
                if (admin.IsNull())
                {
                    return RedirectToError("没有找到对应的 维修人员", code: 404);
                }
                ViewBag.IsEdit = true;
            }
            else
            {
                admin = new Peninsula.DataAccess.POCO.Admin();
                admin.MaintenanceStaff = new MaintenanceStaff();
                //admin.MaintenanceStaff.Stores = StoreService.Entities.Select(
                //   s => new SelectListItem()
                //   {
                //       Value = s.Id,
                //       Text = s.Name
                //   }).ToList();
                admin.MaintenanceStaff.ItemTypes = ItemTypeService.Entities.Select(
                   m => new SelectListItem()
                   {
                       Value = m.Id,
                       Text = m.Name
                   }).ToList();
                ViewBag.IsEdit = false;
            }


            ViewBag.AllRoles = RoleManager.RoleProvider.Entities.Where(r => r.RoleName == roleName);
            string PageTitle = ViewBag.IsEdit ? "编辑维修人员" : "创建维修人员";
            SetPageTitle(PageTitle);
            //SetBreadcrumb(parentName: "账户管理");
            SetBreadcrumb(currentName: PageTitle, parentName: "维修人员", parentUrl: Url.Action("Index", "MaintenanceStaff"));
            //SetBreadcrumb(parentName: "账户管理");
            return View(admin);
        }

        /// <summary>
        /// 编辑或新增维修人员
        /// </summary>
        /// <param name="isEdit"></param>
        /// <param name="postAdmin"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateOrEditMaintenanceStaff(bool isEdit, Peninsula.DataAccess.POCO.Admin postAdmin, string[] role)
        {
            var result = new JsonResultData();

            result.RunWithTry(item =>
            {
                postAdmin.IsSuperAdmin = false;
                postAdmin.IsLockedOut = false;

                // StoreMangerService.Insert(storeManger);

                if (isEdit)
                {
                    ModelState.Remove("Password");
                }
                if (ModelState.IsValid)
                {
                    role = role ?? new string[0];
                    var face = SaveFile("FaceImg", FileSaveRule.AdminFaceSavePath);
                    if (isEdit)
                    {
                        var adminEntity = AdminManager.Get(a => a.Id == postAdmin.Id);
                        adminEntity.FaceImgPath = face ?? adminEntity.FaceImgPath;
                        adminEntity.MaintenanceStaff.StoreId = StoreMangerService.GetById(AdminSession.AdminEntity.StoreMangerId).StoreId;
                        adminEntity.MaintenanceStaff.ItemTypeId = postAdmin.MaintenanceStaff.ItemTypeId;
                        MaintenanceStaffService.Update(adminEntity.MaintenanceStaff);
                        postAdmin.MaintenanceStafId = adminEntity.MaintenanceStafId;
                        ValueCopyHelper.CopyProperty(adminEntity, postAdmin, false,
                            nameof(postAdmin.TrueName),
                            nameof(postAdmin.Email),
                            nameof(postAdmin.Phone),
                            nameof(postAdmin.MaintenanceStafId),
                            nameof(postAdmin.IsSuperAdmin),
                            nameof(postAdmin.IsLockedOut));


                        adminEntity.SetUpdateInfo(AdminSession.AdminEntity.UserName);

                        //删除旧的角色
                        adminEntity.Roles.Where(r => !role.Contains(r.Id)).ToList().ForEach(r => adminEntity.Roles.Remove(r));
                        //添加新角色
                        RoleManager.All().Where(r => role.Contains(r.Id))
                            .ForEach(r => adminEntity.Roles.Add(r));

                        AdminManager.Update(adminEntity);
                        result.Success = true;
                        result.RedirectUrl = Url.Action("Index");
                        result.AddMessage("保存成功！");
                    }
                    else
                    {
                        Admin adminM = AdminManager.AdminProvider.Get(m => m.UserName == postAdmin.UserName);
                        if (adminM.IsNull())
                        {
                            MaintenanceStaff mintenanceStaff = new MaintenanceStaff();
                            mintenanceStaff.StoreId = StoreMangerService.GetById(AdminSession.AdminEntity.StoreMangerId).StoreId;
                            mintenanceStaff.ItemTypeId = postAdmin.MaintenanceStaff.ItemTypeId;
                            postAdmin.MaintenanceStafId = mintenanceStaff.Id;
                            postAdmin.MaintenanceStaff = mintenanceStaff;
                            postAdmin.FaceImgPath = face;
                            RoleManager.All().Where(r => role.Contains(r.Id))
                                .ForEach(r => postAdmin.Roles.Add(r));

                            postAdmin.SetCreateAndUpdateInfo(AdminSession.AdminEntity.UserName);

                            AdminManager.Add(postAdmin);
                            result.Success = true;
                            result.RedirectUrl = Url.Action("Index");
                            result.AddMessage("保存成功！");
                        }
                        else
                        {
                            result.Success = false;
                            result.AddMessage("用户名已存在！");
                        }
                        
                    }

                    
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });

            return Json(result);
        }

        /// <summary>
        /// 删除维修人员
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(string id)
        {

            JsonResultData result = new JsonResultData();
            result.RunWithTry(c =>
            {
                string MaintenanceStaffId = AdminManager.GetById(id).MaintenanceStafId;
                var isDelete = AdminManager.Delete(a => a.Id == id);
                if (!isDelete)
                {
                    c.AddMessage("删除失败");
                }
                isDelete = MaintenanceStaffService.Delete(MaintenanceStaffId) > 0;
                c.Success = isDelete;
                c.AddMessage("删除" + (isDelete ? "成功" : "失败"));
                if (isDelete)
                {
                    c.ReloadPage = true;
                }
            });
            return Json(result);
        }


        /// <summary>
        /// 订单跟踪--维修人员
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public ActionResult OrderTrackingForMaintenanceStaff(Web.Models.RepairOrder.RepairOrderPagedListModel viewModel) {
            SetBreadcrumb(currentName: "订单跟踪");
            SetPageTitle("订单跟踪");
            string storeId = MaintenanceStaffService.GetById(AdminSession.AdminEntity.MaintenanceStafId).StoreId;
            IQueryable<RepairOrder> query = RepairOrderService.Entities.Where(r => (r.Status == OrderStatus.Sent|| r.Status == OrderStatus.OnTheWay||
            r.Status==OrderStatus.RepairFinished
            )&& r.StoreId == storeId && r.MaintenanceStaffId == AdminSession.Identity);
            if (viewModel.Keyword.IsNotNullAndNotWhiteSpace())
            {
                query = query.Where(r => r.Name.Contains(viewModel.Keyword) || r.ItemType.Name.Contains(viewModel.Keyword));
            }
            if (viewModel.msOrderStatus.HasValue)
            {
                query = query.Where(r => r.Status.ToString() == viewModel.msOrderStatus.ToString());
            }
            viewModel.PagedList = query.OrderByDescending(s => s.UpdatedTime).ToPagedList(viewModel.PageIndex, viewModel.Size);
            viewModel.QueryParameter = GetParameterFromQueryString();

            return View(viewModel);

        }


        /// <summary>
        /// 订单更改为在路上
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult OrderSent(string id) {

            JsonResultData result = new JsonResultData();

            result.RunWithTry(order => {

                if (ModelState.IsValid)
                {
                    RepairOrder repairOrder = RepairOrderService.GetById(id);
                    if (repairOrder.IsNull())
                    {
                        order.Success = false;
                        order.AddMessage("订单未存在！");
                    }
                    if (repairOrder.Status != OrderStatus.Sent)
                    {
                        order.Success = false;
                        order.AddMessage("订单已派遣");
                    }
                   
                    MaintenanceStaff maintenanceStaff = MaintenanceStaffService.GetById(AdminSession.AdminEntity.MaintenanceStafId);
                    repairOrder.StoreId = maintenanceStaff.StoreId;
                    repairOrder.Status = OrderStatus.OnTheWay;
                    repairOrder.SetUpdateInfo(AdminSession.AdminUserName);
                    order.Success = RepairOrderService.Update(repairOrder) > 0;
                    order.AddMessage("状态修改" + (order.Success ? "成功" : "失败"));
                    if (order.Success)
                    {
                        order.RedirectUrl = Url.Action("OrderTrackingForMaintenanceStaff");
                    }
                }
                else
                {
                    order.AddModelValidErrorMessage(ModelState);
                }

            });

            return Json(result);
        }

        /// <summary>
        /// 维修人员更改订单状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ChangeOrderStatus(string id) {

            RepairOrder order = RepairOrderService.GetById(id);
            RepairOrderCreateOrEditModel model = new RepairOrderCreateOrEditModel()
            {
                Id = order.Id,
                Status=order.Status        
            };

            SetBreadcrumb($"更改订单状态 - {order.Name}({order.ItemType.Name})", parentName: "订单跟踪", parentUrl: Url.Action("OrderTrackingForMaintenanceStaff"));
            SetPageTitle("更改订单状态");
            return View(model);
        }


        /// <summary>
        /// /维修人员更改订单状态
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ChangeOrderStatus(RepairOrderCreateOrEditModel post) {

            JsonResultData result = new JsonResultData();

            result.RunWithTry(order => {

                if (ModelState.IsValid)
                {
                    RepairOrder repairOrder = RepairOrderService.GetById(post.Id);
                    if (repairOrder.IsNull())
                    {
                        order.Success = false;
                        order.AddMessage("订单未存在！");
                    }
                    repairOrder.Status = post.Status;
                    if (repairOrder.Status==OrderStatus.RepairFinished||repairOrder.Status==OrderStatus.HhouseholdToGoOut)
                    {
                        repairOrder.EndTime = DateTime.Now;
                    }
                    if (repairOrder.Status == OrderStatus.RepairFinished&&post.Price!=0)
                    {

                        repairOrder.Price = post.Price;
                    }
                    else if (repairOrder.Status == OrderStatus.RepairFinished && post.Price == 0)
                    {
                        order.AddMessage("订单状态为“维修完”---价格必须填写且必须大于0！！");
                        return;
                    }
                    repairOrder.MMessage = post.MMessage;               
                    repairOrder.SetUpdateInfo(AdminSession.AdminUserName);
                    order.Success = RepairOrderService.Update(repairOrder) > 0;
                    order.AddMessage("状态修改" + (order.Success ? "成功" : "失败"));
                    if (order.Success)
                    {
                        order.RedirectUrl = Url.Action("OrderTrackingForMaintenanceStaff");
                    }
                }
                else
                {
                    order.AddModelValidErrorMessage(ModelState);
                }

            });

            return Json(result);
        }



        /// <summary>
        /// 完成订单列表
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public ActionResult AlreadyPaidDetalis(Web.Models.RepairOrder.RepairOrderPagedListModel viewModel)
        {

            SetBreadcrumb(currentName: "完成订单");
            SetPageTitle("完成订单");
            string storeId = MaintenanceStaffService.GetById(AdminSession.AdminEntity.MaintenanceStafId).StoreId;
            IQueryable<RepairOrder> query = RepairOrderService.Entities.Where(r => r.Status==OrderStatus.AlreadyPaid && r.StoreId == storeId && r.MaintenanceStaffId == AdminSession.Identity&&r.isDeleteForM==false);
            if (viewModel.Keyword.IsNotNullAndNotWhiteSpace())
            {
                query = query.Where(r => r.Name.Contains(viewModel.Keyword) || r.ItemType.Name.Contains(viewModel.Keyword));
            }
            viewModel.PagedList = query.OrderByDescending(s => s.UpdatedTime).ToPagedList(viewModel.PageIndex, viewModel.Size);
            viewModel.QueryParameter = GetParameterFromQueryString();
            return View(viewModel);
        }

        /// <summary>
        /// 逻辑删除订单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DeleteRepaiOrder(string id)
        {

            JsonResultData result = new JsonResultData();
            result.RunWithTry(c =>
            {
                var order = RepairOrderService.GetById(id);
                if (order.IsNull())
                {
                    c.Success = false;
                    c.AddMessage("未有此订单");
                }
                order.isDeleteForM = true;
                order.SetUpdateInfo(AdminSession.AdminUserName);
                c.Success = RepairOrderService.Update(order) > 0;
                if (c.Success)
                {
                    c.AddMessage("删除成功");
                    c.ReloadPage = true;
                }
            });
            return Json(result);

        }

        /// <summary>
        /// 维修人员统计
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult MaintenanceStaffTotal() {

            SetBreadcrumb(currentName: "订单统计");
            SetPageTitle("订单统计");
            TotalYearModel model = new TotalYearModel();
            return View();
        }

        /// <summary>
        /// 维修人员统计
        /// </summary>
        /// <param name="post"></param>
        /// <returns></returns>
        public JsonResult MaintenanceStaffTotal(TotalYearModel post) {

            JsonResultData data = new JsonResultData();
            var year = HttpContext.Request.Form["dateKeyWord"];
            if (year == "")
            {
                data.Success = false;
               // data.AddMessage("统计年份不能为空！");
                return Json(data);
            }
            DateTime StartTotalTime = new DateTime(int.Parse(year), 1, 1);


            //添加横坐标
            foreach (var item in CateporyMonth)
            {
                list.listCatepory.Add(item);
            }

            Series number = new Series()
            {
                id = 0,
                name = "订单数量",
                type = "bar",
                data = new List<double>(),
                itemStyle = new itemStyle { normal = new normal { color = "#2EC7C9" } },
                markPoint = new markPoint { data = new List<data>() { new data { type = "max", name = "最大值" }, new data { type = "min", name = "最小值" } } },
                markLine = new markLine { data = new List<data>() { new data { type = "average", name = "平均值" } } }

            };

            Series money = new Series()
            {
                id = 1,
                name = "订单钱款",
                type = "bar",
                data = new List<double>(),
                itemStyle = new itemStyle { normal = new normal { color = "#FFBB73" } },
                markPoint = new markPoint { data = new List<data>() { new data { type = "max", name = "最大值" }, new data { type = "min", name = "最小值" } } },
                markLine = new markLine { data = new List<data>() { new data { type = "average", name = "平均值" } } }

            };

 

            if (StartTotalTime.Year == DateTime.Now.Year)//今年
            {
                IQueryable<MaintenanceStaffRestatistics> query = MaintenanceStaffRestatisticsService.Entities;
                for (DateTime dt = StartTotalTime; dt < DateTime.Now; dt = dt.AddMonths(1))
                {

                    query = query.Where(q => q.TotalDateTime.Value.Year== dt.Year && q.TotalDateTime.Value.Month == dt.Month && q.MaintenanceStaffId == AdminSession.Identity);
                    var maintenanceStaffestatistics = query.SingleOrDefault();
                    if (query.Count() == 0)
                    {
                        number.data.Add(0);
                        money.data.Add(0);
                    }
                    else
                    {
                        number.data.Add(maintenanceStaffestatistics.Number);
                        money.data.Add(maintenanceStaffestatistics.TotalPrice.AsDouble());
                    }
                }


            }
            else if (StartTotalTime.Year < DateTime.Now.Year) //过去
            {
                DateTime FinishDateTime = StartTotalTime.AddYears(1);
                IQueryable<MaintenanceStaffRestatistics> query = MaintenanceStaffRestatisticsService.Entities;
                for (DateTime dt = StartTotalTime; dt < FinishDateTime; dt = dt.AddMonths(1))
                {
                    query = query.Where(q => q.TotalDateTime.Value.Year == dt.Year && q.TotalDateTime.Value.Month == dt.Month && q.MaintenanceStaffId ==AdminSession.Identity);
                    var maintenanceStaffestatistics = query.SingleOrDefault();
                    if (query.Count() == 0)
                    {
                        number.data.Add(0);
                        money.data.Add(0);
                    }
                    else
                    {
                        number.data.Add(maintenanceStaffestatistics.Number);
                        money.data.Add(maintenanceStaffestatistics.TotalPrice.AsDouble());
                    }

                }

            }
            else if (StartTotalTime.Year > DateTime.Now.Year)//将来
            {

            }
            else
            {

            }
            list.listLegend.Add(number.name);
            list.listLegend.Add(money.name);
            list.listSeries.Add(number);
            list.listSeries.Add(money);
            return Json(list);
        }


        /// <summary>
        /// 线下支付
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult OfflinePayments(string id)
        {

            JsonResultData result = new JsonResultData();
            result.RunWithTry(c =>
            {
                var order = RepairOrderService.GetById(id);
                if (order.IsNull())
                {
                    c.Success = false;
                    c.AddMessage("未有此订单");
                }
                order.Status = OrderStatus.AlreadyPaid;
                order.SetUpdateInfo(AdminSession.AdminUserName);
                c.Success = RepairOrderService.Update(order) > 0;
                if (c.Success)
                {
                    c.AddMessage("支付成功");
                    c.RedirectUrl = Url.Action("AlreadyPaidDetalis");
                }
            });
            return Json(result);

        }
    }
}